package com.jiahe.blog.common.handler;

import com.alibaba.fastjson.JSON;
import com.jiahe.blog.model.StatusConst;
import com.jiahe.blog.model.response.BlogResponse;
import com.jiahe.blog.utils.ServletUtils;
import com.jiahe.blog.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 用户权限处理
 */
@Slf4j
@Component
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException {
        String msg = StringUtils.format("请求访问：{}，没有权限，无法访问资源", request.getRequestURI());
        log.error(msg);
        ServletUtils.renderString(response, JSON.toJSONString(BlogResponse.error(StatusConst.AUTHORIZED, msg)));
    }
}
